package org.fastsyncer.core.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.constant.CommonConstant;
import org.fastsyncer.common.util.ApplicationUtil;
import org.fastsyncer.common.util.PropertiesUtil;
import org.fastsyncer.common.util.SHA1Util;
import org.fastsyncer.core.service.ConfigService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

/**
 * @ClassName: ConfigServiceImpl 
 * @Description: 系统参数配置
 * @author AE86
 * @date: 2017年8月2日 下午5:20:27
 */
@Service("ConfigService")
public final class ConfigServiceImpl implements ConfigService{

    /**
     * 默认可以修改的参数集合
     */
    private static final List<String> PARAMS = new ArrayList<String>();
    
    static {
        /**
         * #worker单次任务最多执行条数 fastsyncer.worker.task.max.number=500
         * #worker每次批量执行条数 fastsyncer.worker.batch.number=50 #worker线程数
         * fastsyncer.worker.thread.number=10
         */
        PARAMS.add(CommonConstant.WORKER_TASK_MAX_NUMBER);
        PARAMS.add(CommonConstant.WORKER_BATCH_NUMBER);
        PARAMS.add(CommonConstant.WORKER_THREAD_NUMBER);
        PARAMS.add(CommonConstant.REST_APPROVAL_IP);
    }
    
    @Override
    public Map<String, String> getSystemParams() throws Exception {
        // 获取系统参数
        Map<String, String> map = null;
        final List<String> list = PARAMS;
        if (list != null && !list.isEmpty()) {
            int size = list.size();
            map = new HashMap<String, String>(size);
            String p = null;
            for (int i = 0; i < size; i++) {
                p = list.get(i);
                map.put(p, ApplicationUtil.getKey(p));
            }
        }
        return map;
    }

    @Override
    public String updateSystemParams(String params) throws Exception {
        JSONObject pStr = new JSONObject(params);
        if (null != pStr) {
            // 获取参数个数
            JSONArray names = pStr.names();
            int nLen = names.length();
            if (nLen < 1) {
                throw new Exception("系统参数为空!");
            }

            Map<String, String> map = new HashMap<String, String>();
            for (int i = 0; i < nLen; i++) {
                String pName = names.getString(i);
                String pVal = pStr.getString(pName);
                if (StringUtils.isBlank(pVal)) {
                    continue;
                }

                // 设置参数名，参数值
                map.put(pName, pVal);
            }

            // 保存参数
            this.update(map);
        }
        return "系统参数修改成功!";
    }

    @Override
    public String updateAdminPwd(String oldPwd, String newPwd) throws Exception {
        //检查密码是否正确
        String rpwd = ApplicationUtil.getKey(CommonConstant.CONFIG_ADMIN_PWD);
        // 加密
        oldPwd = SHA1Util.b64_sha1(oldPwd);
        if (!rpwd.equals(oldPwd)) {
            throw new IllegalArgumentException("密码错误.");
        }
        newPwd = SHA1Util.b64_sha1(newPwd);
        ApplicationUtil.setKey(CommonConstant.CONFIG_ADMIN_PWD, newPwd);

        // 持久化到本地磁盘
        PropertiesUtil.update(ApplicationUtil.getKey(CommonConstant.CONFIG_PATH_APPLICATION_PROPERTIES), 
                CommonConstant.CONFIG_ADMIN_PWD, newPwd);
        return "个人密码修改成功!";
    }
    
    private void update(Map<String, String> params) {
        // 检查是否有参数
        if (params == null || params.size() < 1) {
            return;
        }

        // 默认可以修改的参数集合
        HashMap<String, String> map = new HashMap<>();
        for (Map.Entry<String, String> p : params.entrySet()) {
            String key = p.getKey();

            // 如果沒有运行修改则跳过
            if (!PARAMS.contains(key)) {
                continue;
            }

            map.put(key, p.getValue());

            // 修改系统参数
            ApplicationUtil.setKey(key, p.getValue());
        }

        // 持久化到本地磁盘
        PropertiesUtil.update(ApplicationUtil.getKey(CommonConstant.CONFIG_PATH_APPLICATION_PROPERTIES), map);
    }
}
